
//中间件- 验证token返回id
module.exports = app => {
    const assert = require('http-assert');
    const Users = require('../models/User');
    //登陆
    app.post('/admin/api/Login', async (req, res) => {
        const { username, password } = req.body;
        const admin = await Users.findOne({ username }).select('+password');
        assert(admin, 401, '用户不存在')
        let power = admin.power != "no"
        console.log('tag', power)
        assert(power, 408, '用户被禁用了')
        const pass = require('bcryptjs').compareSync(password, admin.password)
        assert(pass, 401, '密码错误')
        const token = require('jsonwebtoken').sign({
            exp: Math.floor(Date.now() / 1000) + (60 * 60),  //一小时过时
            id: String(admin._id)
        }, app.get('token'))
        res.send({
            token,
            name: admin.name,
            img: admin.img
        })
    })

    let auth = require(`./auth`)(app, ["admin", "user"])
    //上传文件，文件夹

    const multer = require("multer");
    const fs = require('fs');
    const uploadweb = multer({ dest: __dirname + "../../web" })  //要上传的路径  __dirname 是当前的路径 
    app.use("/admin/api/uploadweb", auth, uploadweb.any(), async (req, res) => {
        const file = req.files;
        var newName = file[0].path.slice(0, file[0].path.indexOf(file[0].filename)); //更换成上传的名字
        // console.log(req.body)
        var relativePath = req.body.relativePath;
        if (relativePath.indexOf("/") == -1) {
            newName += relativePath
        } else {
            var filePath = __dirname + "../../web/" + relativePath.slice(0, relativePath.lastIndexOf("/"));
            console.log(filePath)
            if (fs.existsSync(filePath)) {
                console.log('该路径已存在');
            } else {
                console.log('该路径不存在');
                mkdir(filePath);
            }
            // fs.mkdir( __dirname + "../../upload/" + req.body.relativePath.slice(0, req.body.relativePath).indexOf("/"))
            newName += relativePath.replace(RegExp("/", "g"), "\\")
        }

        console.log(newName)
        fs.rename(file[0].path, newName, function (err) { //修改名字
            if (err) {
                res.send('上传失败')
            } else {
                res.send('上传成功')
            }
            res.end();
        })
        // 
        // console.log(file)
        // // file.url = `http://localhost:3000/admin/api/upload/${file.filename}`
        // // file.url = `/admin/api/upload/${file.filename}`
        // res.send(file)
    })

    const pathLib = require('path');
    const uploadapp = multer({ dest: __dirname + "../../app" })  //要上传的路径  __dirname 是当前的路径 
    app.use("/admin/api/uploadapp", auth, uploadapp.any(), async (req, res) => {
        const file = req.files;
        file.url = `http://localhost:3000/admin/api/upload/${req.body.relativePath}`
        // file.url = `/admin/api/upload/${file.filename}`
        var newName = file[0].path.slice(0, file[0].path.indexOf(file[0].filename)) + req.body.relativePath;
        // console.log(req)
        console.log("newName", newName)
        fs.rename(file[0].path, newName, function (err) { //修改名字
            if (err) {
                res.send('上传失败')
            } else {
                res.send(file.url)
            }
            res.end();
        })
        // res.send(file)
    })

    const dirCache = {};
    function mkdir(filePath) {
        const arr = filePath.split('/');
        let dir = arr[0];
        for (let i = 1; i < arr.length; i++) {
            if (!dirCache[dir] && !fs.existsSync(dir)) {
                dirCache[dir] = true;
                fs.mkdirSync(dir);
            }
            dir = dir + '/' + arr[i];
        }
        fs.mkdirSync(filePath)
    }
    const excels = require(`../models/excels`);

    // const newDB = require('./newDB');
    const uploadxlsx = multer({ dest: __dirname + "../../xlsx" })  //要上传的路径  __dirname 是当前的路径 
    app.use("/admin/api/uploadxlsx", uploadxlsx.any(), async (req, res) => {
        const file = req.files;
        file.url = `http://localhost:3000/admin/api/upload/${req.body.relativePath}`
        // file.url = `/admin/api/upload/${file.filename}`
        var newName = file[0].path.slice(0, file[0].path.indexOf(file[0].filename)) + req.body.relativePath;
        // console.log(req)
        console.log("newName", newName)
        fs.rename(file[0].path, newName, async function (err) { //修改名字
            if (err) {
                res.send('上传失败')
            } else {
                let data = excelConfig(newName);
                data.url = file.url;
                // console.log(data);
                const excel = await excels.create({ date: new Date(), excel: data });
                // let da = await excels.findById("60bcdc38c4e17d0ce0aec703")
                // console.log(excel)
                res.send({ id: excel._id })
            }
            res.end();
        })
        // res.send(newName);
    })


    //https://www.cnblogs.com/jackson-yqj/p/10314471.html
    var node_xlsx = require('node-xlsx');
    function excelConfig(excel_Dir) {
        let obj = node_xlsx.parse(excel_Dir);// 支持的excel文件类有.xlsx .xls .xlsm .xltx .xltm .xlsb .xlam等
        let excelObj = obj[0].data;//取得第一个excel表的数据
        let insertData = [];//存放数据
        let daexcelHeader = excelObj[0]
        //循环遍历表每一行的数据
        for (var i = 1; i < excelObj.length; i++) {
            var rdata = excelObj[i];
            var CityObj = new Object();
            // ["id" : "101010100","provinceZh" : "北京","leaderZh" : "北京","cityZh" : "北京","cityEn" : "beijing"]
            for (var j = 0; j < rdata.length; j++) {
                CityObj[daexcelHeader[j]] = rdata[j]
                // console.log(rdata[j])
            }
            insertData.push(CityObj)
        }
        // console.log(insertData)
        return {
            headers: daexcelHeader,
            body: insertData
        }
    }
}




